programming4us
           
 
 
Programming

Parallel Programming with Microsoft .Net : Parallel Tasks - Variations (part 2)

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
11/28/2010 2:41:15 PM
3. Waiting for the First Task to Complete

The Task class includes a method named Task.WaitAll that allows you to wait for a set of tasks to complete. However, you can also wait for the first task to complete by calling the Task.WaitAny method.


Note:

Use Task.WaitAny as a way to wait for at least one task in a set of tasks to complete.


Here’s an example.

var taskIndex = -1;
Task[] tasks = new Task[]
{
Task.Factory.StartNew(DoLeft),
Task.Factory.StartNew(DoRight),
Task.Factory.StartNew(DoCenter)
};
Task[] allTasks = tasks;
// Print completion notices one by one as tasks finish.
while (tasks.Length > 0)
{
taskIndex = Task.WaitAny(tasks);
Console.WriteLine("Finished task {0}.", taskIndex + 1);
tasks = tasks.Where((t) => t != tasks[taskIndex]).ToArray();
}
// Observe any exceptions that might have occurred.
try
{
Task.WaitAll(allTasks);
}
catch (AggregateException ae)
{
...
}

This example shows how you can use the WaitAny method to be notified when the first of a group of tasks completes. The code prints a line to the console output after each task finishes. The while loop exits after all the tasks finish.

Note:

Exceptions are never observed by the WaitAny method. However, you must make sure that all exceptions are eventually observed using one of the techniques that are described in the section, Section 3.3.2, earlier in this chapter.


You need to observe any exceptions that may have occurred, but note that exceptions are never observed by the WaitAny method. Instead, you should add a step that checks for exceptions whenever you use the WaitAny method. Although this example uses the WaitAll method to observe exceptions, you could also use the Exception property or the Wait method for this purpose. The IsFaulted property of the Task class can be used to check to see whether an unhandled exception occurred within a task.

4. Speculative Execution

Speculative execution is a variation that occurs where you perform an operation in anticipation of a particular result. For example, you might predict that the current computation being run will output the value 42, and you start the next computation that depends on this computation’s result by using 42 as the input. If the first computation ends with 42, you’ve now gained parallelism by successfully starting the dependent operation well in advance of when you otherwise could have. If the first computation results in something other than 42, you can restart the second operation using the correct value.

Another example of speculative execution occurs when you execute more than one asynchronous operation in parallel but need just one of the operations to complete before proceeding. Imagine, for example, that you use three different search tasks to search for an item. After the fastest task finds the item, you don’t need to wait for the other searches to complete. In cases like, this you wait for the first task to complete and usually cancel the remaining tasks. However, you should always observe any exceptions that might have occurred in any of the tasks.

Here’s an example.

SpeculativeInvoke(SearchLeft, SearchRight, SearchCenter);
This example executes three delegate methods in parallel. Only one of the delegates needs to complete for the operation to succeed, so the tasks that did not finish first are canceled. The SpeculativeInvoke method executes each of the delegates in the params array argument. Its implementation is shown in the following code.
public static void SpeculativeInvoke(
params Action<CancellationToken>[] actions)
{
var cts = new CancellationTokenSource();
var token = cts.Token;
var tasks =
(from a in actions
select Task.Factory.StartNew(() => a(token), token))
.ToArray();
// Wait for fastest task to complete.
Task.WaitAny(tasks);
// Cancel all of the slower tasks.
cts.Cancel();
// Wait for cancellation to finish and observe exceptions.
try
{
Task.WaitAll(tasks);
}
catch (AggregateException ae)
{
// Filter out the exception caused by cancellation itself.
ae.Flatten().Handle(e => e is OperationCanceledException);
}
finally
{
if (cts != null) cts.Dispose();
}
}

The WaitAny method does not observe unhandled task exceptions. This is because you need the returned index from WaitAny to know which task completed (potentially by throwing an exception). Therefore, this example also makes a call to the WaitAll method after canceling the tasks that did not finish first. This causes all unhandled task exceptions to be observed in the current thread. The code catches the aggregate exception that is thrown by WaitAll and removes the OperationCanceledException instances. If there are no remaining unhandled exceptions, the code proceeds normally. Otherwise, the remaining unhandled exceptions are rethrown as the inner exceptions of a new aggregate exception.

5. Creating Tasks with Custom Scheduling

You can customize the details of how tasks in .NET are scheduled and run by overriding the default task scheduler that’s used by the task factory methods. For example, you can provide a custom task scheduler as an argument to one of the overloaded versions of the Task Factory.StartNew method.


Note:

You can customize the way tasks are scheduled.


There are some cases where you might want to override the default scheduler. The most common case occurs when you want your task to run in a particular thread context. This can happen when you use objects provided by libraries, such as Windows Presentation Foundation (WPF), that impose thread affinity constraints. Other cases occur when the load-balancing heuristics of the default task scheduler don’t work well for your application.

Unless you specify otherwise, any new tasks will use the current task scheduler, which is the value of the static property Task Scheduler.Current. In other words, subtasks inherit the task scheduler of the enclosing task context. Unless otherwise specified, new top-level tasks (and, consequently, their subtasks) use the default task scheduler, which is the value of the static property TaskScheduler. Default. The default task scheduler is tightly integrated with the .NET thread pool and handles a wide variety of operating conditions. It’s a good choice for most applications. The Task Scheduler class’s FromCurrentSynchronizationContext static method returns a task scheduler object that schedules the task to run wherever the current thread’s SynchronizationContext property indicates. This is sometimes the current thread, but not necessarily. This task scheduler is useful in cases of thread affinity. Not every thread has a current synchronization context, and there is no API to get a task scheduler that runs in the synchronization context of a thread other than the current thread. For example, you can’t use the FromCurrentSynchronizationContext method if you’re trying to schedule a task in a Windows service’s main thread.

You can implement your own task scheduler class.

Other -----------------
- Parallel Programming with Microsoft .Net : Parallel Tasks - An Example
- Parallel Programming with Microsoft .Net : Parallel Tasks - The Basics
- jQuery 1.3 : The jQuery UI plugin library
- jQuery 1.3 : The Form plugin
- jQuery 1.3 : How to use a plugin
- jQuery 1.3 : Sharing a plugin with the world
- Auditing an Existing Site to Identify SEO Problems (part 3) - Fixing an Internal Linking Problem
- Auditing an Existing Site to Identify SEO Problems (part 2) - The Importance of Keyword Reviews
- Auditing an Existing Site to Identify SEO Problems (part 1 - Elements of an Audit
- First Stages of SEO : Defining Your Site’s Information Architecture
- First Stages of SEO : The Major Elements of Planning
- Understanding Your Audience and Finding Your Niche
- Developing an SEO Plan Prior to Site Development
- Setting SEO Goals and Objectives
- jQuery 1.3 : Developing plugins - Adding a selector expression
- jQuery 1.3 : Developing plugins - Method parameters
- The LINQ Set Operators
- iPhone 3D Programming : Vertices and Touch Points - Creating a Wireframe Viewer (part 3)
- iPhone 3D Programming : Vertices and Touch Points - Creating a Wireframe Viewer (part 2)
- iPhone 3D Programming : Vertices and Touch Points - Creating a Wireframe Viewer (part 1)
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
programming4us programming4us